//package com.plian.system.service.dg.impl;
//
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
//import com.baomidou.mybatisplus.core.metadata.IPage;
//import com.baomidou.mybatisplus.core.toolkit.Wrappers;
//import com.plian.Tools.*;
//import com.plian.Tools.pagedata.PageData;
//import com.plian.system.constant.sys.FormStatusConstant;
//import com.plian.system.constant.sys.FormTypeConstant;
//import com.plian.system.entity.dg.PolicyLegalLibrary;
//import com.plian.system.entity.sys.BehavioralData;
//import com.plian.system.entity.sys.Org;
//import com.plian.system.mapper.dg.PolicyLegalLibraryMapper;
//import com.plian.system.model.CommonCode;
//import com.plian.system.model.ListResult;
//import com.plian.system.model.ObjResult;
//import com.plian.system.mybatis.base.BaseFlowService;
//import com.plian.system.mybatis.base.BaseServiceImpl;
//import com.plian.system.mybatis.search.SearchEntity;
//import com.plian.system.mybatis.search.SearchParamEntiy;
//import com.plian.system.mybatis.search.TokenSearch;
//import com.plian.system.mybatis.support.Condition;
//import com.plian.system.mybatis.support.Query;
//import com.plian.system.service.dg.IPolicyLegalLibraryService;
//import com.plian.system.service.sys.behavioral.IBehavioralDataService;
//import com.plian.system.service.sys.code.IFormCodeService;
//import com.plian.system.service.sys.file.FileService;
//import com.plian.system.service.sys.orgzation.IOrgService;
//import com.plian.system.service.wf.FormWorkflowService;
//import com.plian.system.vo.dg.PolicyLegalLibraryVO;
//import com.plian.system.wrapper.dg.PolicyLegalLibraryWrapper;
//import lombok.AllArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang.exception.ExceptionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import javax.servlet.http.HttpServletResponse;
//import java.util.*;
//import java.util.concurrent.locks.Lock;
//import java.util.concurrent.locks.ReentrantLock;
//
//import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;
//
///**
// * 制度政策法规库管理 service
// */
//@Service
//@AllArgsConstructor
//@Slf4j
//public class PolicyLegalLibraryServiceImpl extends BaseServiceImpl<PolicyLegalLibraryMapper, PolicyLegalLibrary> implements IPolicyLegalLibraryService, BaseFlowService {
//
//    private IFormCodeService formCodeService;
//
//    private FileService fileService;
//
//    private FormWorkflowService formWorkflowService;
//
//    private final IOrgService orgService;
//
//    private final PolicyLegalLibraryWrapper policyLegalLibraryWrapper;
//
//    private final Lock lock = new ReentrantLock();
//
//    private IBehavioralDataService behavioralDataService;
//
//    @Override
//    public boolean submit(PolicyLegalLibraryVO policyLegalLibraryVO) {
//        boolean flag = false;
//        PolicyLegalLibrary policyLegalLibrary = policyLegalLibraryWrapper.voToEntity(policyLegalLibraryVO);
//        if (!Optional.ofNullable(policyLegalLibrary.getId()).isPresent()) {
//            flag = true;
//            policyLegalLibrary.setFormType(String.valueOf(FormTypeConstant.DG_POLICY_LEGAL_LIBRARY));
//            policyLegalLibrary.setCode(formCodeService.getCode(FormTypeConstant.DG_POLICY_LEGAL_LIBRARY));
//            //政策法规文体编号
//            policyLegalLibrary.setPolicyRegulatoryDocumentsCode(formCodeService.getCode(FormTypeConstant.DG_POLICY_LEGAL_LIBRARY));
//            policyLegalLibrary.setBusinessManager(TokenUtil.getTokenUserId());
//            policyLegalLibrary.setQueryTimes(0);
//            policyLegalLibrary.setDownloadTimes(0);
//        }
//        if (!Optional.ofNullable(policyLegalLibrary.getStatus()).isPresent()) {
//            policyLegalLibrary.setStatus(FormStatusConstant.UNREVIEWED);
//        }
//        if (CollectionUtil.isNotEmpty(policyLegalLibrary.getMajorIndustryIds())) {
//            policyLegalLibrary.setMajorIndustryId(String.join(StringPool.COMMA, policyLegalLibrary.getMajorIndustryIds()));
//        }
//        boolean result = super.saveOrUpdate(policyLegalLibrary);
//        if (flag) {
//            fileService.saveAll(String.valueOf(policyLegalLibrary.getId()), policyLegalLibrary.getDocList());
//        } else {
//            fileService.edit(String.valueOf(policyLegalLibrary.getId()), policyLegalLibrary.getDocList());
//        }
//        return result;
//    }
//
//    @Override
//    public PolicyLegalLibraryVO detail(PolicyLegalLibrary policyLegalLibrary) {
//        PolicyLegalLibrary entity = getById(policyLegalLibrary.getId());
//        return policyLegalLibraryWrapper.entityToVO(entity);
//    }
//
//    @Override
//    public ListResult<PolicyLegalLibraryVO> list(Query query) {
//        List<SearchEntity> entityList = query.getSearch();
//        if (query.getAscs() == null && query.getDescs() == null) {
//            query.setDescs("create_time");
//        }
//        QueryWrapper<PolicyLegalLibrary> queryWrapper = SearchParamEntiy.getQueryWrapper(
//                Condition.getQueryWrapper(new PolicyLegalLibrary()), entityList
//        );
//        TokenSearch<PolicyLegalLibrary> tokenSearch = new TokenSearch<>();
//		tokenSearch.addTokenQuery(queryWrapper, query);
//        IPage<PolicyLegalLibrary> pages = page(Condition.getPage(query), queryWrapper);
//        List<PolicyLegalLibraryVO> enterpriseAssociationVOS = policyLegalLibraryWrapper.entityToVO(pages.getRecords());
//
//        if (CollectionUtil.isNotEmpty(enterpriseAssociationVOS)){
//            //是否看过
//            String orgId = TokenUtil.getTokenOrgId();
//            String userId = TokenUtil.getTokenUserId();
//            List<BehavioralData> behavioralDataList= behavioralDataService.list(Wrappers.<BehavioralData>lambdaQuery().eq(BehavioralData::getUserId, userId).eq(BehavioralData::getOrgId, orgId).eq(BehavioralData::getActionType, 1));
//            if (CollectionUtil.isNotEmpty(behavioralDataList)){
//                enterpriseAssociationVOS.forEach(assocation ->{
//                    if (Optional.ofNullable(assocation.getFormType()).isPresent() ){
//                        Optional<BehavioralData> any = behavioralDataList.stream().filter(behavioral -> assocation.getId().toString().equals(behavioral.getFormId()) && assocation.getFormType().equals(behavioral.getFormType())).findAny();
//                        if (any.isPresent()){
//                            assocation.setIsLook(1);
//                        }else {
//                            assocation.setIsLook(0);
//                        }
//                    }else {
//                        assocation.setIsLook(1);
//                    }
//                });
//            }else {
//                enterpriseAssociationVOS.forEach(assocation ->{
//                    if (Optional.ofNullable(assocation.getId()).isPresent() && Optional.ofNullable(assocation.getFormType()).isPresent() ){
//                        assocation.setIsLook(0);
//                    }else {
//                        assocation.setIsLook(1);
//                    }
//                });
//            }
//        }
//        ListResult<PolicyLegalLibraryVO> listResult = new ListResult<>(CommonCode.SUCCESS);
//        listResult.setList(enterpriseAssociationVOS);
//        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
//        return listResult;
//    }
//
//    @Override
//    public boolean changeAgingStatus(PolicyLegalLibraryVO vo) {
//        List<String> ids = vo.getIds();
//        if (CollectionUtil.isNotEmpty(ids)) {
//            String agingStatus = vo.getAgingStatus();
//            boolean result = update(new LambdaUpdateWrapper<PolicyLegalLibrary>().set(PolicyLegalLibrary::getAgingStatus, agingStatus)
//                    .in(PolicyLegalLibrary::getId, Func.toLongList(StringUtils.join(ids, StringPool.COMMA))));
//            return result;
//        }
//        return false;
//    }
//
//    @Override
//    public boolean deleteLogic(List<Long> ids) {
//        for (Long id : ids) {
//            PolicyLegalLibrary policyLegalLibrary = getById(id);
//            if (policyLegalLibrary == null) {
//                return false;
//            } else if (policyLegalLibrary.getStatus() != null &&
//                    (policyLegalLibrary.getStatus() != FormStatusConstant.STASH && policyLegalLibrary.getStatus() != FormStatusConstant.UNREVIEWED)) {
//                return false;
//            }
//            formWorkflowService.deleteProcessInstance(String.valueOf(id));
//        }
//        return super.deleteLogic(ids);
//    }
//
//    @Transactional(rollbackFor = Throwable.class)
//    public boolean downloadTest(String id) {
//        return increaseCount(id, 2);
//    }
//
//    @Override
//    @Transactional(rollbackFor = Throwable.class)
//    public boolean preview(String id) {
//        return increaseCount(id, 1);
//    }
//
//    /**
//     * 次数增加
//     *
//     * @return
//     * @param:
//     * @date: 2023/4/10 6:08 PM
//     * @author: jatpeo
//     */
//    private boolean increaseCount(String id, Integer type) {
//        lock.lock();
//        try {
//            PolicyLegalLibrary library = getById(id);
//            if (type == 1) {
//                Integer queryTimes = library.getQueryTimes();
//                library.setQueryTimes(++queryTimes);
//            } else {
//                Integer downloadTimes = library.getDownloadTimes();
//                library.setDownloadTimes(++downloadTimes);
//            }
//            updateById(library);
//            return true;
//        } catch (Exception e) {
//            log.error("error:次数增加失败！{}", e);
//        } finally {
//            lock.unlock();
//        }
//        return false;
//    }
//
//    @Override
//    @Transactional(rollbackFor = Throwable.class)
//    public void download(String id, HttpServletResponse response) {
//        PageData doc = new PageData();
//        try {
//            doc.put("parentId", id);
//            ObjResult objResult = fileService.listParentId(doc);
//            if (objResult.getCode() == CommonCode.SUCCESS.code()) {
//                PageData pageData = objResult.getPageData();
//                List<HashMap> listDoc = (List<HashMap>) pageData.get("list_doc");
//                doc.put("id", listDoc.get(0).get("id"));
//                //记录次数
//                boolean result = increaseCount(id, 2);
//                if (result) {
//                    fileService.fileDown(doc, response);
//                }
//            }
//
//        } catch (Exception e) {
//            throw new RuntimeException("error:下载失败" + e);
//        }
//    }
//
//
//    @Override
//    public HashMap<String, Object> commit(String id) {
//        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);
//        //将需要提交的流程变量返回，用于工作流侧
//        return new HashMap<String, Object>();
//    }
//
//    public Boolean finish(String id) {
//        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
//    }
//
//    @Override
//    public Boolean reject(String id, int formState, String comment) {
//        return handleStatus(Long.valueOf(id), formState);
//    }
//
//    @Override
//    public void goBackToStash(String formId) {
//        handleStatus(Long.valueOf(formId), UNREVIEWED);
//    }
//
//    @Override
//    public List<PageData> findByIds(List<String> formIds) {
//        List<PolicyLegalLibrary> policyLegalLibraries = list(new LambdaQueryWrapper<PolicyLegalLibrary>()
//                .in(PolicyLegalLibrary::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA))));
//        List<PolicyLegalLibraryVO> policyLegalLibraryVOList = policyLegalLibraryWrapper.entityToVO(policyLegalLibraries);
//        List<PageData> pageDataList = new ArrayList<>();
//        Org org = orgService.getById(TokenUtil.getTokenOrgId());
//        try {
//            if (CollectionUtil.isNotEmpty(policyLegalLibraryVOList)) {
//                for (PolicyLegalLibraryVO vo : policyLegalLibraryVOList) {
//                    PageData pd = new PageData();
//                    pd.put("id", vo.getId());
//                    pd.put("UNITNAME", org.getName());
//                    pd.put("APPLICANTNAME", vo.getCreateUser());
//                    pd.put("applicantId", vo.getCreateUser());
//                    pd.put("applyOrganizationId", org.getId());
//                    pd.put("formType", FormTypeConstant.DG_POLICY_LEGAL_LIBRARY);
//                    pd.put("orgName", org.getName());
//                    pageDataList.add(pd);
//                }
//            }
//            return pageDataList;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//        return pageDataList;
//    }
//
//    @Override
//    public List<Integer> getFormType() {
//        return Arrays.asList(FormTypeConstant.DG_POLICY_LEGAL_LIBRARY);
//    }
//
//    /**
//     * 统一处理状态机事件方法
//     *
//     * @param id           主键
//     * @param updateStatus 更新状态
//     * @return boolean
//     */
//    private Boolean handleStatus(Long id, int updateStatus) {
//        try {
//            PolicyLegalLibrary policyLegalLibrary = getById(id);
//            if (updateStatus == FormStatusConstant.FINISH) {
//                policyLegalLibrary.setApprovedUser(TokenUtil.getTokenUserId());
//                Date now = DateUtil.now();
//                policyLegalLibrary.setApprovedTime(now);
//            }
//            policyLegalLibrary.setStatus(updateStatus);
//            updateById(policyLegalLibrary);
//            return true;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return false;
//        }
//    }
//}
//
